<template>
  <div id="uppic">
    <slot></slot>
    <div style="position:absolute;top:0;left:0;width:100%;height:80px;" @click.stop>
      <button type="button" id="dx_upload_btn" @click="uploadFile" style="display: none;">选择文件</button>
      <!--<input ref="file" type="file" accept="image/*" @change="readImage">-->
    </div>

    <div id="uppicBox" ref="uppicBox" v-show="isuppicBox">
      <div class="imageBox">
        <img id="pic-img" ref="picImg" :src="img.src"
             :style="{
             'transform':'translate3d('+transform.x+'px,'+transform.y+'px,0px) scale('+transform.scale+','+transform.scale+')',
             '-webkit-transform':'translate3d('+transform.x+'px,'+transform.y+'px,0px) scale('+transform.scale+','+transform.scale+')',
             '-moz-transform':'translate3d('+transform.x+'px,'+transform.y+'px,0px) scale('+transform.scale+','+transform.scale+')',
             ' -ms-transform':'translate3d('+transform.x+'px,'+transform.y+'px,0px) scale('+transform.scale+','+transform.scale+')',
             '-o-transform':'translate3d('+transform.x+'px,'+transform.y+'px,0px) scale('+transform.scale+','+transform.scale+')',
             'transition':'transform '+duration+'ms',
             '-moz-transition':'transform '+duration+'ms',
             '-webkit-transition':'transform '+duration+'ms',
             '-o-transition':'transform '+duration+'ms',
             'width':img.w+'px','height':img.h+'px','margin-left':img.w/-2+'px','margin-top':img.h/-2+'px'

             }">
        <div class="thumbBox box"
             :class="{'bgshadow':isbg}"
             ref="thumbBox"
             :style="{'width':Cwidth+'px','height':Cheight+'px','margin-left':0-Cwidth/2+'px','margin-top':0-Cheight/2+'px'}">
          <div class="angle1"></div>
          <div class="angle2"></div>
          <div class="angle3"></div>
          <div class="angle4"></div>
          <!--<div class="line1"></div>-->
          <!--<div class="line2"></div>-->
          <!--<div class="line3"></div>-->
          <!--<div class="line4"></div>-->
        </div>
      </div>
      <div class="bottom" @click.stop>
        <span @click="cancel">取消</span>
        <span @click="clip" class="fr">选取</span>
      </div>
    </div>
  </div>
</template>
<script>
  import "../../assets/lib/exif.js"
  import Hammer from "hammerjs"
  export default {
    name: 'Uppic',
    data() {
      return {
        transform: {
          'scale': 1,
          'x': 0,
          'y': 0
        },
        isuppicBox: false,
        isbg: false,
        duration: 0,
        Cwidth: 0,
        Cheight: 0,
        img: {
          Yh: 0,
          Yw: 0,
          h: 0,
          w: 0,
          src: '',
          Orientation: 1
        },
        x: 0,
        y: 0,
        initScale: 0,
        imgRotate: 1 //[ 1：旋转90°]
      }
    },
    props: {
      callback: Function,
      width: {
        type: Number,
        default: 200,
        validator: function (value) {
          return value !== 0
        }
      },
      height: {
        type: Number,
        default: 200
      },
      imgSrc: {
        type: String,
      },
      data: {
        type: Object,
        default: function () {
          return {}
        }
      }
    },
    methods: {

      /*初始化手势方法*/
      init(e) {
        let me = this;
        me.isuppicBox = true;
        let picImg = me.$refs.picImg;
        me.img.Yw = picImg.naturalWidth;
        me.img.Yh = picImg.naturalHeight;
        // EXIF.getData(picImg, function () {
        //     me.img.Orientation = EXIF.getTag(this, 'Orientation') || 1;
        //     me.sizeimg();
        // });
        //me.img.Orientation = 1;
        me.sizeimg();
        document.body.onresize = me.sizeimg;
        let mc = new Hammer.Manager(this.$refs.uppicBox);
        mc.add(new Hammer.Pan({threshold: 0, pointers: 0}));
        mc.add(new Hammer.Pinch({threshold: 0})).recognizeWith(mc.get('pan'));
        mc.add(new Hammer.Tap({event: 'doubletap', taps: 2}));
        mc.add(new Hammer.Tap());
        mc.on("doubletap", me.doubletap);
        mc.on("pinchstart pinchmove", me.pinchin);
        mc.on("panstart panmove", me.Pan);
        mc.on('panend', me.panend);
      },

      sizeimg: function () {
        let me = this;
        let w = document.body.clientWidth;
        let h = document.body.clientHeight;
        let Yh = me.img.Yh;
        let Yw = me.img.Yw;
        let Width, Height;
        /* 设置截取框长宽 */
        if (w * me.height < h * me.width) {
          Width = w - 40;
          Height = Width / me.width * me.height;
        } else {
          Height = h - 40;
          Width = Height / me.height * me.width;
        }
        this.Cwidth = Width;
        this.Cheight = Height;
        /*设置原图片 iPhone图片 */
        if (Yw * Height < Yh * Width) {
          /* 以宽为基准缩放 */
          me.img.w = Width;
          me.img.h = Yh * Width / Yw;
        } else {
          /* 以高为基准缩放 */
          me.img.h = Height;
          me.img.w = Yw * Height / Yh;
        }
        // alert(Width + ',' + Height + ',' + Yw + ',' + Yh + ',' + me.img.w + ',' + me.img.h)
      },

      /*双击方法*/
      doubletap(e) {
        let scale = this.transform['scale'];
        if (scale < 4) {
          this.transform['scale'] = scale * 1.2;
        }
        console.log('双击')
      },

      /*缩放方法*/
      pinchin(ev) {
        if (ev.type === 'pinchstart') {
          this.initScale = this.transform.scale || 1;
        }
        let scale = this.initScale * ev.scale;
        if (scale < 4) {
          this.transform.scale = scale;
        }
        console.log('缩放')
      },

      /*移动*/
      Pan(ev) {
        if (ev.type === 'panstart') {
          this.x = this.transform['x'] || 0;
          this.y = this.transform['y'] || 0;
        }
        this.transform.x = this.x + ev.deltaX;
        this.transform.y = this.y + ev.deltaY;

        this.isbg = true;
        console.log('移动')
      },

      /*判断是否超过边界线*/
      panend() {
        let me = this;
        let scale = this.transform.scale;
        let tx = this.transform.x;
        let ty = this.transform.y;

        let w = this.img.w * scale;
        let h = this.img.h * scale;
        let ww = this.Cwidth;
        let hh = this.Cheight;

        let left = (w - ww) / 2;
        let right = (ww - w) / 2;
        let top = (h - hh) / 2;
        let bottom = (hh - h) / 2;

        if (scale < 1) {
          scale = 1;
          if (h > w) {
            tx = 0
          } else {
            ty = 0
          }
        } else {
          if (tx > left) {
            tx = left;
            console.log('过left底线');
          } else if (tx < right) {
            tx = right;
            console.log('过right底线');
          }
          if (ty > top) {
            ty = top;
            console.log('过top底线');
          } else if (ty < bottom) {
            ty = bottom;
            console.log('过bottom底线');
          }
        }
        this.duration = 300;
        this.transform.scale = scale;
        this.transform.x = tx;
        this.transform.y = ty;
        setTimeout(function () {
          me.isbg = false;
          me.duration = 0;
        }, 300)
      },
      /* 取消 */
      cancel() {
        this.isuppicBox = false;
        this.img.src = '';
        this.transform = {
          'scale': 1,
          'x': 0,
          'y': 0
        };
        this.$refs.picImg = '';
        this.$emit('get-edit-net-img',false);
      },

      /*裁剪 */
      clip() {
        let me = this;
        let self = this;

        // 浮点数加法 a + b
        function accAdd(a, b) {
          let c, d, e;
          try {
            c = a.toString().split(".")[1].length;
          } catch (f) {
            c = 0;
          }
          try {
            d = b.toString().split(".")[1].length;
          } catch (f) {
            d = 0;
          }
          return e = Math.pow(10, Math.max(c, d)), (accMul(a, e) + accMul(b, e)) / e;
        }

        // 浮点数减法 a - b
        function accSub(a, b) {
          let c, d, e;
          try {
            c = a.toString().split(".")[1].length;
          } catch (f) {
            c = 0;
          }
          try {
            d = b.toString().split(".")[1].length;
          } catch (f) {
            d = 0;
          }
          return e = Math.pow(10, Math.max(c, d)), (accMul(a, e) - accMul(b, e)) / e;
        }

        // 浮点数乘法 a * b
        function accMul(a, b) {
          let c = 0,
            d = a.toString(),
            e = b.toString();
          try {
            c += d.split(".")[1].length;
          } catch (f) {
          }
          try {
            c += e.split(".")[1].length;
          } catch (f) {
          }
          return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
        }

        // 浮点数除法 a / b
        function accDiv(a, b) {
          let c, d, e = 0,
            f = 0;
          try {
            e = a.toString().split(".")[1].length;
          } catch (g) {
          }
          try {
            f = b.toString().split(".")[1].length;
          } catch (g) {
          }
          return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), accMul(c / d, Math.pow(10, f - e));
        }

        // 1. 框缩放了 （width,height）->(Cwidth,Cheight)
        // 2. 图片相对于框缩放了 (Yw,Yh) -> (w,h)
        // 3. 图片缩放 scale
        // 4. 图片偏移 tx ty

        // 图片的大小  width,height
        // 相对于原图的缩放比例
        let imgScale = accDiv(self.img.w, self.img.Yw);
        let scale = accMul(self.transform.scale, imgScale);
        // 相对于原图的使用宽高
        // 图片放大相当于框变小
        // 图片缩小相当于框变大
        // 当前框 *  当前图片/图片原尺寸
        let c_w = accMul(self.Cwidth, 1); // 默认剪切 框的大小
        let c_h = accMul(self.Cheight, 1);
        // 相对于原图使用的左偏移 上偏移
        let y_1 = accDiv(accSub(accMul(self.img.h, self.transform.scale), self.Cheight), 2);
        let x_1 = accDiv(accSub(accMul(self.img.w, self.transform.scale), self.Cwidth), 2);
        y_1 = accSub(y_1, self.transform.y).toFixed(4);
        x_1 = accSub(x_1, self.transform.x).toFixed(4);

        let url;
        url = self.img.src + '|imageMogr2/thumbnail/!' + parseInt(scale * 100) + 'p' + '|imageMogr2/crop/!' + c_w + 'x' + c_h + 'a' + x_1 + 'a' + y_1;

        console.log("url:"+url);
        me.$emit('get-edit-img', url);
        me.$emit('get-edit-net-img',false);
        me.isuppicBox = false;
        // document.getElementById('uppic').innerHTML = url;
        // document.getElementById('uppic').innerHTML = '<div style="position: fixed;top:10%;left:0;right:0;bottom:0;background: blue;padding:10px 10px;">' +
        //   '<img style="width:100%;height:auto;" src="' + url + '"/></div>';

      },

      /*上传图片点击方法*/
      uploadFile(image) {
        let self = this;
        // alert(image);
        console.log("image:"+image);
        self.img.src = image + '?imageMogr2/auto-orient';
        self.$refs.picImg.onload = self.init;
      },
    },
    components: {},
    watch: {},
    mounted() {

    }
  }
</script>
<style scoped>
  html,
  body {
    height: 100%;
  }

  #uppic {
    position: absolute;
    width: 100%;
    height: 100%;
    /*zoom: 3;*/
    z-index: 10000;
    overflow: hidden;
  }

  #uppic .file {
    position: absolute;
    width: 100%;
    height: 100%;
    opacity: 0;
    top: 0;
    left: 0;
    z-index: 10000;
    cursor: pointer;
  }

  #uppic #uppicBox {
    display: block;
  }

  #uppic #uppicBox .thumbBox {
    width: 100%;
    border: 1px solid #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    box-shadow: 0 0 0 1000px rgba(0, 0, 0, 0.8);
  }

  #uppic #uppicBox .thumbBox .line1,
  #uppic #uppicBox .thumbBox .line2 {
    width: 100%;
    height: 1px;
    position: absolute;
    background: #fff;
    left: 0;
    top: 33.33%;
  }

  #uppic #uppicBox .thumbBox .line2 {
    top: 66.66%;
  }

  #uppic #uppicBox .thumbBox .line3,
  #uppic #uppicBox .thumbBox .line4 {
    width: 1px;
    height: 100%;
    position: absolute;
    background: #fff;
    left: 33.33%;
    top: 0;
  }

  #uppic #uppicBox .thumbBox .line4 {
    left: 66.66%;
  }

  #uppic #uppicBox .thumbBox .angle1,
  #uppic #uppicBox .thumbBox .angle2,
  #uppic #uppicBox .thumbBox .angle3,
  #uppic #uppicBox .thumbBox .angle4 {
    position: absolute;
    width: 15px;
    height: 15px;
  }

  #uppic #uppicBox .thumbBox .angle1 {
    left: -2px;
    top: -2px;
    border-top: 2px solid #fff;
    border-left: 2px solid #fff;
  }

  #uppic #uppicBox .thumbBox .angle2 {
    left: -2px;
    bottom: -2px;
    border-bottom: 2px solid #fff;
    border-left: 2px solid #fff;
  }

  #uppic #uppicBox .thumbBox .angle3 {
    right: -2px;
    top: -2px;
    border-top: 2px solid #fff;
    border-right: 2px solid #fff;
  }

  #uppic #uppicBox .thumbBox .angle4 {
    right: -2px;
    bottom: -2px;
    border-bottom: 2px solid #fff;
    border-right: 2px solid #fff;
  }

  #uppic #uppicBox .bgshadow {
    box-shadow: 0 0 0 1000px rgba(0, 0, 0, 0.2);
  }

  #uppic #uppicBox .bottom {
    position: absolute;
    top: 0;
    bottom: 10%;
    left: 0;
    right: 0;
    background: rgba(255, 255, 255, 0.05);
    font-size: 26px;
    color: #fff;
    padding: 10px 0;
    z-index: 999999;
  }

  #uppic #uppicBox .bottom span {
    padding: 10px;
    display: inline-block;
    float: left;
  }

  #uppic #uppicBox .bottom .fr {
    float: right;
  }

  #uppic #uppicBox #pic-img {
    position: absolute;
    top: 50%;
    left: 50%;
    width: auto;
  }

  /*不兼容ios position:fixed*/
  #uppicBox, .imageBox {

    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999999;
    /*overflow: hidden;*/
    background: #000;
    cursor: pointer;
  }

</style>
